//package com.laiketui.payment.service.dubbo;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//
//
//import com.laiketui.domain.distribution.DistributionWithdrawModel;
//import com.laiketui.domain.lktconst.DictionaryConst;
//import com.laiketui.domain.log.RecordDetailsModel;
//import com.laiketui.domain.log.RecordModel;
//import com.laiketui.domain.mch.MchModel;
//import com.laiketui.domain.message.MessageLoggingModal;
//import com.laiketui.payment.common.v3Dto.MerchantConfig;
//import com.google.common.collect.Maps;
//import com.laiketui.common.mapper.*;
//import com.laiketui.domain.config.ConfigModel;
//import com.laiketui.domain.order.OrderModel;
//import com.laiketui.common.api.PublicOrderService;
//import com.laiketui.domain.user.User;
//import com.laiketui.domain.user.WithdrawModel;
//import com.laiketui.domain.vo.MainVo;
//import com.laiketui.payment.common.AppConst;
//import com.laiketui.payment.util.AesUtil;
//import com.laiketui.payment.util.WechatPayUtils;
//import com.laiketui.payment.api.WechatPayService;
//import com.laiketui.root.annotation.DubboApiMethod;
//import com.laiketui.core.exception.LaiKeAPIException;
//import com.laiketui.domain.lktconst.ErrorCode;
//import com.laiketui.core.lktconst.GloabConst;
//import com.laiketui.core.utils.tool.DataUtils;
//import com.laiketui.core.utils.tool.WxOpenIdUtils;
//import com.laiketui.root.common.BuilderIDTool;
//import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
//import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
//import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
//import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
//import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
//import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
//import com.wechat.pay.java.core.exception.ServiceException;
//import com.wechat.pay.java.service.transferbatch.TransferBatchService;
//import com.wechat.pay.java.service.transferbatch.model.*;
//import github.wxpay.sdk.WXPayUtil;
//import org.apache.commons.collections.MapUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.util.EntityUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.io.ByteArrayInputStream;
//import java.io.IOException;
//import java.math.BigDecimal;
//import java.net.URLDecoder;
//import java.security.PrivateKey;
//import java.util.*;
//import java.util.stream.Collectors;
//import java.util.stream.Stream;
//
//import static com.laiketui.core.lktconst.DictionaryConst.OrderPayType.*;
//import static com.laiketui.core.lktconst.ErrorCode.BizErrorCode.API_OPERATION_FAILED;
//
//
///**
// * 微信支付
// * @author wangxian
// */
//@Service("wechatPayServiceV3DubboImpl")
//public class WechatPayServiceV3DubboImpl extends PayServiceAdapter implements WechatPayService {
//
//    private final Logger logger = LoggerFactory.getLogger(WechatPayServiceV3DubboImpl.class);
//
//    @Autowired
//    private PaymentConfigModelMapper paymentConfigModelMapper;
//
//    @Autowired
//    private OrderModelMapper orderModelMapper;
//
//    @Autowired
//    private PublicOrderService publicOrderService;
//
//    @Autowired
//    private MerchantConfig merchantConfig;
//
//    @Autowired
//    private ConfigModelMapper configModelMapper;
//
//    @Autowired
//    private WithdrawModelMapper withdrawModelMapper;
//
//    @Autowired
//    private UserBaseMapper userBaseMapper;
//
//    @Autowired
//    private MchModelMapper mchModelMapper;
//
//    @Autowired
//    private MessageLoggingModalMapper messageLoggingModalMapper;
//
//    @Autowired
//    private RecordDetailsModelMapper recordDetailsModelMapper;
//
//    @Autowired
//    private RecordModelMapper recordModelMapper;
//
//
//    @Value("${wechat.payurl.app_wechat}")
//    private String appWechatUrl;
//
//    @Value("${wechat.payurl.jsapi_mini_wechat}")
//    private String jsapiWechatUrl;
//
//    @Value("${wechat.payurl.h5_wechat}")
//    private String h5WechatUrl;
//
//    @Value("${wechat.payurl.native_wechat}")
//    private String nativeWechatUrl;
//
//    @Value("${wechat.gzh.redirect_uri}")
//    private String redirect_uri;
//
//    /**
//     * 初始化
//     * @param params
//     * @throws IOException
//     */
//    public CloseableHttpClient setup(Map params) throws IOException {
//        /** 加载商户私钥（privateKey：私钥字符串）*/
//        String privateKey = MapUtils.getString(params,"key_pem");
//        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes(GloabConst.Chartset.UTF_8)));
//        /** 加载平台证书（mchId：商户号,mchSerialNo：商户证书序列号,apiV3Key：V3秘钥）*/
//        String mchId = MapUtils.getString(params,"mch_id");
//        String certContext = MapUtils.getString(params,"cert_pem");
//        String mchSerialNo = getSerialNo(certContext);
//        // TODO json新增序列号apiV3Key
//        String apiV3Key = MapUtils.getString(params,"apiV3Key");
//        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
//                new WechatPay2Credentials(mchId, new PrivateKeySigner(mchSerialNo, merchantPrivateKey)),apiV3Key.getBytes(GloabConst.Chartset.UTF_8));
//        return WechatPayHttpClientBuilder.create()
//                .withMerchant(mchId, mchSerialNo, merchantPrivateKey)
//                .withValidator(new WechatPay2Validator(verifier)).build();
//    }
//
//    /**
//     * 创建订单 H5/APP/Native/JSAPI/
//     * @param params
//     * @throws Exception
//     */
//    public String createOrder(Map params) throws Exception{
//        logger.info("微信支付下单apiv3:{}",params);
//        CloseableHttpClient httpClient = setup(params);
//        CloseableHttpResponse response = null;
//        try {
//            //请求URL
//            String apiUrl = DataUtils.getStringVal(params,"apiUrl");
//            String description = DataUtils.getStringVal(params,"description");
//            String mchId = DataUtils.getStringVal(params,"mchid");
//            String appId = DataUtils.getStringVal(params,"appid");
//            String notifyUrl = DataUtils.getStringVal(params,"notify_url");
//            String payOrderNo = DataUtils.getStringVal(params,"payOrderNo");
//            int total = DataUtils.getIntegerVal(params,"total",1)*100;
//
//            /** 支付类型 jsapi和小程序 才有 */
//            String payClass = DataUtils.getStringVal(params,"payClass");
//            String payer = "";
//            if ( ORDERPAYTYPE_MINI_WECHAT.equals(payClass) ||
//                    ORDERPAYTYPE_JSAPI_WECHAT.equals(payClass)){
//                String openid = DataUtils.getStringVal(params,"openid");
//                payer = "\"payer\": {"
//                        + "\"openid\": \""+openid+"\"" + "},";
//            }
//
//            HttpPost httpPost = new HttpPost(apiUrl);
//            // 请求body参数
//            String reqdata = "{"
//                    + "\"amount\": {"
//                    + "\"total\": "+total+","
//                    + "\"currency\": \"CNY\""
//                    + "},"
//                    + "\"mchid\": \""+mchId+"\","
//                    + "\"description\": \""+description+"\","
//                    + "\"notify_url\": \""+notifyUrl+"\","
//                    + payer
//                    + "\"out_trade_no\": \""+payOrderNo+"\","
//                    + "\"appid\": \""+appId+"\" }";
//
//            StringEntity entity = new StringEntity(reqdata);
//            entity.setContentType("application/json");
//            httpPost.setEntity(entity);
//            httpPost.setHeader("Accept", "application/json");
//            //完成签名并执行请求
//            response = httpClient.execute(httpPost);
//            String resultStr = EntityUtils.toString(response.getEntity());
//            int statusCode = response.getStatusLine().getStatusCode();
//            logger.info("微信支付返回信息,响应code = {},响应body = " ,statusCode,resultStr);
//            if (statusCode == 200 || statusCode == 204) {
//                return resultStr;
//            }  else {
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.API_OPERATION_FAILED,"微信支付失败","createOrder");
//            }
//        } finally {
//            response.close();
//            httpClient.close();
//            logger.info("微信支付下单apiv3结束！");
//        }
//    }
//
//    /**
//     * @param params
//     * @return
//     * @throws LaiKeAPIException
//     */
//    @Override
//    public Map<String, Object> wechatAppPay(Map  params) throws LaiKeAPIException {
//        Map<String,Object> resultMap = new HashMap<>();
//        try{
//            String mchId = DataUtils.getStringVal(params,"mchid");
//            String appId = DataUtils.getStringVal(params,"appid");
//
//            JSONObject resultJson = JSONObject.parseObject(createOrder(params));
//            /** 获取预支付订单id */
//            String prepayId = resultJson.getString("prepay_id");
//
//            if(StringUtils.isNotEmpty(prepayId)){
//                /**结果处理*/
//                resultMap.put("appid",appId);
//                resultMap.put("partnerid",mchId);
//                resultMap.put("prepayid",prepayId);
//                resultMap.put("package","Sign=WXPay");
//                String nonceStr = WXPayUtil.generateNonceStr();
//                resultMap.put("noncestr",nonceStr);
//                Long timestamp = System.currentTimeMillis()/1000;
//                resultMap.put("timestamp",timestamp);
//                String signatureStr = Stream.of(appId, String.valueOf(timestamp), nonceStr, prepayId)
//                        .collect(Collectors.joining("\n", "", "\n"));
//                String paySign = WechatPayUtils.sign(params,signatureStr);
//                resultMap.put("paySign",paySign);
//                return resultMap;
//            } else {
//                String message = resultJson.getString("message");
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.API_OPERATION_FAILED,message,"wechatAppPay");
//            }
//        } catch (Exception e){
//            e.printStackTrace();
//            logger.error(e.getMessage());
//            throw new LaiKeAPIException(ErrorCode.BizErrorCode.API_OPERATION_FAILED,"微信支付失败","wechatAppPay");
//        }
//    }
//
//
//    /**
//     * H5支付
//     * @param params
//     * @return
//     * @throws LaiKeAPIException
//     */
//    @Override
//    public Map<String, Object> weChatWapPay(Map  params) throws LaiKeAPIException {
//        Map<String,Object> resultMap = new HashMap<>(16);
//        try{
//            //异常情况下的结果处理
//            resultMap.put("data",createOrder(params));
//        }catch (Exception e){
//            e.printStackTrace();
//            logger.error(e.getMessage());
//            throw new LaiKeAPIException(ErrorCode.BizErrorCode.API_OPERATION_FAILED,"微信支付失败","weChatWapPay");
//        }
//        return resultMap;
//    }
//
//
//    @Override
//    public Map<String, Object> wechatPcQrPay(Map  params) throws LaiKeAPIException {
//        Map<String,Object> resultMap = new HashMap<>(16);
//        try{
//            resultMap.put("data",createOrder(params));
//        }catch (Exception e){
//            e.printStackTrace();
//            logger.error(e.getMessage());
//            throw new LaiKeAPIException(ErrorCode.BizErrorCode.API_OPERATION_FAILED,"微信支付失败","wechatPcQrPay");
//        }
//        return resultMap;
//    }
//
//    /**
//     * 小程序支付
//     * @param params
//     * @return
//     * @throws LaiKeAPIException
//     */
//    @Override
//    public Map<String, Object> wechatMiniPay(Map  params) throws LaiKeAPIException {
//        Map<String,Object> resultMap = new HashMap<>();
//        try{
//            resultMap = wechatAppPay(params);
//        }catch (Exception e){
//            e.printStackTrace();
//            logger.error(e.getMessage());
//            throw new LaiKeAPIException(ErrorCode.BizErrorCode.API_OPERATION_FAILED,"微信支付失败","wechatMiniPay");
//        }
//        return resultMap;
//    }
//
//    /**
//     * jsapi支付
//     * @param params
//     * @return
//     * @throws LaiKeAPIException
//     */
//    @Override
//    public Map<String, Object> wechatJsapiPay(Map  params) throws LaiKeAPIException {
//        Map<String,Object> resultMap = new HashMap<>();
//        try{
//            resultMap = (params);
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error(e.getMessage());
//            throw new LaiKeAPIException(ErrorCode.BizErrorCode.API_OPERATION_FAILED,"微信支付失败","wechatJsapiPay");
//        }
//        return resultMap;
//    }
//
//    /**
//     * 此方法在这里做分发
//     * @param params
//     * @return
//     * @throws LaiKeAPIException
//     */
////    @DubboApiMethod(apiKey = "com.laike.payment.wechat.apiv3.slink.pay",
////            login = true, module = AppConst.MODULE_NAME, version = "1.0.0")
////    @Transactional
////    @Override
////    public Map<String, Object> pay(Map  params) throws LaiKeAPIException {
////        Map<String,Object> resultMap = new HashMap<>();
////        try{
////            //微信app支付 默认app支付
////            String payClass = ORDERPAYTYPE_APP_WECHAT;
////            String className = DataUtils.getStringVal(params,"type",payClass);
////            int storeId = DataUtils.getIntegerVal(params,"storeId");
////            //获取支付信息 缓存
////            String paymentJson = paymentConfigModelMapper.getPaymentConfigInfo(storeId,className);
////            paymentJson = paymentJson.replaceAll("%2B","\\+");
////            JSONObject payJson = JSONObject.parseObject(paymentJson);
////            Map data = payJson.getInnerMap();
////
////            //TODO 优化订单支付金额 直接从后台获取 订单支付成功后台放入中间件 这里直接根据订单号来取 只存订单号和金额
////            // 目前是从前端传来的
////            String appId = DataUtils.getStringVal(params,"appid");
////            String appSecret = DataUtils.getStringVal(params,"appsecret");
////            String code = DataUtils.getStringVal(params,"code");
////            switch (className){
////                /** 微信小程序支付 */
////                case ORDERPAYTYPE_MINI_WECHAT:
////                    data.put("payClass",ORDERPAYTYPE_MINI_WECHAT);
////                    data.put("apiUrl",jsapiWechatUrl);
////                    //TODO 测试
////                    data.put("openid", WxOpenIdUtils.getMiniOpenid(appId,appSecret,code));
////                    resultMap = this.wechatMiniPay(data);
////                    break;
////                /** 微信公众号支付 */
////                case ORDERPAYTYPE_JSAPI_WECHAT:
////                    data.put("payClass",ORDERPAYTYPE_JSAPI_WECHAT);
////                    //TODO 测试
////                    data.put("openid", WxOpenIdUtils.getGzhOpenid(appId,appSecret,code));
////                    data.put("apiUrl",jsapiWechatUrl);
////                    resultMap = this.wechatJsapiPay(data);
////                    break;
////                /** 微信二维码支付 */
////                case ORDERPAYTYPE_PC_WECHAT:
////                    data.put("apiUrl",nativeWechatUrl);
////                    resultMap = this.wechatPcQrPay(data);
////                    break;
////                /** 手机H5微信支付 */
////                case ORDERPAYTYPE_H5_WECHAT:
////                    data.put("apiUrl",h5WechatUrl);
////                    resultMap = this.weChatWapPay(data);
////                    break;
////                /** 微信APP支付 */
////                default:
////                    data.put("apiUrl",appWechatUrl);
////                    resultMap = this.wechatAppPay(data);
////            }
////
////        }catch (Exception e){
////            e.printStackTrace();
////            logger.error(e.getMessage());
////            throw new LaiKeAPIException(ErrorCode.BizErrorCode.API_OPERATION_FAILED,"微信支付失败","wechatJsapiPay");
////        }
////        return resultMap;
////    }
//
//
//    @Transactional
//    @Override
//    public Map<String, Object> payBack(Map params) throws LaiKeAPIException {
//        Map resultMap = Maps.newHashMap();
//        try{
//            String notifyJson = MapUtils.getString(params,"notifyJson");
//            String wxPayV3Key = MapUtils.getString(params,"wxPayV3Key");
//            AesUtil aesUtil  = new AesUtil(wxPayV3Key.getBytes(GloabConst.Chartset.UTF_8));
//            JSONObject notifyJsonObj = JSONObject.parseObject(notifyJson);
//            JSONObject resourceJson = notifyJsonObj.getJSONObject("resource");
//            String resultJsonStr = aesUtil.decryptToString(resourceJson.getString("nonce").getBytes(GloabConst.Chartset.UTF_8),
//                    resourceJson.getString("nonce").getBytes(GloabConst.Chartset.UTF_8),resourceJson.getString("ciphertext"));
//
//            /**返回的json结果*/
//            JSONObject resultJson = JSONObject.parseObject(resultJsonStr);
//            /*
//                    {
//                      "transaction_id": "1217752501201407033233368018",
//                      "amount": {
//                        "payer_total": 100,
//                        "total": 100,
//                        "currency": "CNY",
//                        "payer_currency": "CNY"
//                      },
//                      "mchid": "1230000109",
//                      "trade_state": "SUCCESS",
//                      "bank_type": "CMC",
//                      "promotion_detail": [
//                        {
//                          "amount": 100,
//                          "wechatpay_contribute": 0,
//                          "coupon_id": "109519",
//                          "scope": "GLOBALSINGLE",
//                          "merchant_contribute": 0,
//                          "name": "单品惠-6",
//                          "other_contribute": 0,
//                          "currency": "CNY",
//                          "type": "CASHNOCASH",
//                          "stock_id": "931386",
//                          "goods_detail": [
//                            {
//                              "goods_remark": "商品备注信息",
//                              "quantity": 1,
//                              "discount_amount": 1,
//                              "goods_id": "M1006",
//                              "unit_price": 100
//                            },
//                            {
//                              "goods_remark": "商品备注信息",
//                              "quantity": 1,
//                              "discount_amount": 1,
//                              "goods_id": "M1006",
//                              "unit_price": 100
//                            }
//                          ]
//                        },
//                        {
//                          "amount": 100,
//                          "wechatpay_contribute": 0,
//                          "coupon_id": "109519",
//                          "scope": "GLOBALSINGLE",
//                          "merchant_contribute": 0,
//                          "name": "单品惠-6",
//                          "other_contribute": 0,
//                          "currency": "CNY",
//                          "type": "CASHNOCASH",
//                          "stock_id": "931386",
//                          "goods_detail": [
//                            {
//                              "goods_remark": "商品备注信息",
//                              "quantity": 1,
//                              "discount_amount": 1,
//                              "goods_id": "M1006",
//                              "unit_price": 100
//                            },
//                            {
//                              "goods_remark": "商品备注信息",
//                              "quantity": 1,
//                              "discount_amount": 1,
//                              "goods_id": "M1006",
//                              "unit_price": 100
//                            }
//                          ]
//                        }
//                      ],
//                      "success_time": "2018-06-08T10:34:56+08:00",
//                      "payer": {
//                        "openid": "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"
//                      },
//                      "out_trade_no": "1217752501201407033233368018",
//                      "appid": "wxd678efh567hg6787",
//                      "trade_state_desc": "支付失败，请重新下单支付",
//                      "trade_type": "MICROPAY",
//                      "attach": "自定义数据",
//                      "scene_info": {
//                        "device_id": "013467007045764"
//                      }
//                    }
//             */
//            String appid = resultJson.getString("appid");
//            String out_trade_no = resultJson.getString("out_trade_no");
//
//            OrderModel orderModel = new OrderModel();
//            orderModel.setReal_sno(out_trade_no);
//            orderModel = orderModelMapper.selectOne(orderModel);
//            if(orderModel!=null && orderModel.getStatus() < 1){
//                /**更新订单*/
//                resultMap = publicOrderService.payBackUpOrder(orderModel);
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error("微信回调失败",e.getMessage());
//            throw new LaiKeAPIException(API_OPERATION_FAILED,"微信回调失败","payBack");
//        }
//        return resultMap;
//    }
//
//    @Override
//    //该方法wx提现错误须进行管理后台消息提醒不开启事务
////    @Transactional(rollbackFor = Exception.class)
//    public boolean MerchantTransfersToChange(String paramJson) {
//        try {
//            JSONObject jsonObject = JSON.parseObject(paramJson);
//            Integer storeId = jsonObject.getInteger("storeId");
//            String withdrawId = jsonObject.getString("withdrawId");
//            //插件提现
//            String pluginStatus = jsonObject.getString("pluginStatus");
//            if (StringUtils.isNotEmpty(pluginStatus)){
//                return MerchantTransfersToChange(storeId, withdrawId, withdrawId);
//            }
//            WithdrawModel withdrawModel = withdrawModelMapper.selectByPrimaryKey(withdrawId);
//            if (withdrawModel == null){
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TXJLBCZ, "提现记录不存在");
//            }
//            if (withdrawModel.getWithdrawStatus().equals(WithdrawModel.WITHDRAW_STATUS.YHK)){
//                logger.error("【微信零钱提现】提现申请id{}，为银行卡提现", withdrawId);
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SJCW, "数据错误");
//            }
//            //获取用户信息
//            User user = userBaseMapper.selectByUserId(storeId, withdrawModel.getUser_id());
//            if (user == null){
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_YHBCZ, "用户不存在");
//            }
//            String paymentJson = paymentConfigModelMapper.getPaymentConfigInfo(storeId, "wechat_v3_withdraw");
//            paymentJson = URLDecoder.decode(paymentJson, GloabConst.Chartset.UTF_8);
//            JSONObject payJson = JSONObject.parseObject(paymentJson);
//            //微信SDK提供
//            TransferBatchService service =
//                    new TransferBatchService.Builder().config(merchantConfig.getRSAConfig(storeId)).build();
//            InitiateBatchTransferRequest request = new InitiateBatchTransferRequest();
//            String batchName = "";
//            String BatchRemark = "";
//            String OutBatchNo = "";
//            String OutDetailNo = "";
//            //店铺提现
//            if (withdrawModel.getIs_mch() == 1){
//                batchName = "店铺余额提现";
//                BatchRemark =withdrawModel.getName() + "用户进行"  + batchName;
//            }else {
//                //用户提现
//                batchName = "用户余额提现";
//                BatchRemark =withdrawModel.getName() + "用户进行"  + batchName;
//            }
//            //微信金额单位分处理
//            BigDecimal yb = new BigDecimal("100");
//            BigDecimal totalAmount = withdrawModel.getMoney().subtract(withdrawModel.getS_charge());
//            if (totalAmount.compareTo(BigDecimal.ZERO) > 0){
//                totalAmount = totalAmount.multiply(yb);
//            }else {
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SJCW, "数据错误");
//            }
//            //构造请求微信支付发起转账的参数
//            //【批次名称】 该笔批量转账的名称
//            request.setBatchName(batchName);
//            //【商户appid】 申请商户号的appid或商户号绑定的appid（企业号corpid即为此appid）
//            request.setAppid(payJson.getString("appid"));
//            //【商家批次单号】 商户系统内部的商家批次单号，要求此参数只能由数字、大小写字母组成，在商户系统内部唯一
//            request.setOutBatchNo(withdrawModel.getTxsno());
//            //【批次备注】 转账说明，UTF8编码，最多允许32个字符
//            request.setBatchRemark(BatchRemark);
//            //【转账总金额】 转账金额单位为“分”。转账总金额必须与批次内所有明细转账金额之和保持一致，否则无法发起转账操作
//            request.setTotalAmount(totalAmount.longValue());
//            //【转账总笔数】 一个转账批次单最多发起一千笔转账。转账总笔数必须与批次内所有明细之和保持一致，否则无法发起转账操作
//            request.setTotalNum(1);
//
//
//            List<TransferDetailInput> transferDetailInputs = new ArrayList<>();
//            TransferDetailInput transferDetailInput = new TransferDetailInput();
//            //【收款用户openid】 商户appid下，某用户的openid
//            transferDetailInput.setOpenid(user.getWx_id());
//            //【商家明细单号】 商户系统内部区分转账批次单下不同转账明细单的唯一标识，要求此参数只能由数字、大小写字母组成
//            transferDetailInput.setOutDetailNo(withdrawModel.getTxsno() + withdrawId);
//            //【转账金额】 转账金额单位为“分”
//            transferDetailInput.setTransferAmount(totalAmount.longValue());
//            //【转账备注】 单条转账备注（微信用户会收到该备注），UTF8编码，最多允许32个字符
//            transferDetailInput.setTransferRemark(BatchRemark);
//            if (withdrawModel.getMoney().compareTo(new BigDecimal(2000)) >= 0
//                    && StringUtils.isNotEmpty(withdrawModel.getRealname())){
//                transferDetailInput.setUserName(withdrawModel.getRealname());
//            }
//
//            transferDetailInputs.add(transferDetailInput);
//            //【转账明细列表】 发起批量转账的明细列表，最多一千笔
//            request.setTransferDetailList(transferDetailInputs);
//            try {
//                InitiateBatchTransferResponse response = service.initiateBatchTransfer(request);
//                //【微信批次单号】 微信批次单号，微信商家转账系统返回的唯一标识
//                String batchId = response.getBatchId();
//                withdrawModel.setWxOpenId(user.getWx_id());
//                withdrawModel.setWxName(user.getWx_name());
//                withdrawModel.setWxSon(batchId);
//                withdrawModel.setWxStatus(WithdrawModel.WX_STATUS.SUCCESS);
//                withdrawModelMapper.updateByPrimaryKeySelective(withdrawModel);
//            } catch (ServiceException e) {
//                // http请求成功，但是wx接口失败，这里需要根据实际需求处理错误码
//                logger.error("商家转账到零钱错误!");
//                logger.error("错误信息:" + e.getErrorCode() + "," +  e.getErrorMessage());
//                //管理后台消息通知
//                MessageLoggingModal messageLoggingSave = new MessageLoggingModal();
//                messageLoggingSave.setStore_id(storeId);
//                messageLoggingSave.setMch_id(user.getMchId());
//                messageLoggingSave.setTo_url("");
//                messageLoggingSave.setAdd_date(new Date());
//                if (e.getErrorCode().equals("403")){
//                    //商户账户资金不足，请充值后原单重试，请勿更换商家转账批次单号
//                    if (withdrawModel.getIs_mch() == 1){
//                        MchModel mchModel = mchModelMapper.selectByPrimaryKey(user.getMchId());
//                        messageLoggingSave.setType(MessageLoggingModal.Type.TYPE_STORE_WITHDRAWAL);
//                        messageLoggingSave.setParameter(mchModel.getName());
//                        messageLoggingSave.setContent(String.format("ID为%s的店铺申请提现打款余额不足，请及时充值！",mchModel.getId()));
//                    }else {
//                        messageLoggingSave.setType(MessageLoggingModal.Type.TYPE_USER_WITHDRAWAL);
//                        messageLoggingSave.setParameter(user.getUser_name());
//                        messageLoggingSave.setContent(String.format("ID为%s的用户申请提现打款余额不足，请及时充值！", user.getUser_id()));
//                    }
//                }else {
//                    if (withdrawModel.getIs_mch() == 1){
//                        MchModel mchModel = mchModelMapper.selectByPrimaryKey(user.getMchId());
//                        messageLoggingSave.setType(MessageLoggingModal.Type.TYPE_STORE_WITHDRAWAL);
//                        messageLoggingSave.setParameter(mchModel.getName());
//                        messageLoggingSave.setContent(String.format("ID为%s的店铺申请提现打款失败，失败原因:%s",mchModel.getId(),e.getErrorMessage()));
//                    }else {
//                        messageLoggingSave.setType(MessageLoggingModal.Type.TYPE_USER_WITHDRAWAL);
//                        messageLoggingSave.setParameter(user.getUser_name());
//                        messageLoggingSave.setContent(String.format("ID为%s的用户申请提现打款失败，失败原因:%s",user.getUser_id(),e.getErrorMessage()));
//                    }
//                }
//                messageLoggingModalMapper.insertSelective(messageLoggingSave);
//                throw new LaiKeAPIException(e.getErrorCode(), e.getErrorMessage());
//            } catch (LaiKeAPIException l) {
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "MerchantTransfersToChange");
//            }
//        }catch (LaiKeAPIException l) {
//            logger.error("商家转账到零钱异常", l);
//            throw l;
//        }catch (Exception e) {
//            logger.error("商家转账到零钱异常 ", e);
//            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "MerchantTransfersToChange");
//        }
//        return true;
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void QueryBatchTransferOrder(MainVo vo) {
//        try {
//            int storeId = vo.getStoreId();
//            //获取商城商家转账到零钱正在进行中的订单
//            WithdrawModel withdrawModel = new WithdrawModel();
//            withdrawModel.setStore_id(storeId);
//            withdrawModel.setWithdrawStatus(WithdrawModel.WITHDRAW_STATUS.WX);
//            withdrawModel.setWxStatus(WithdrawModel.WX_STATUS.WAIT_PAY);
//            List<WithdrawModel> list = withdrawModelMapper.select(withdrawModel);
//            //已完成
//            int successNum = 0;
//            //失败
//            int failNum = 0;
//            if (list.size() > 0){
//                logger.info("商城id: {}, 正在进行中的商城商家转账到零钱订单数量{}",storeId, list.size());
//                //微信SDK提供
//                TransferBatchService service =
//                        new TransferBatchService.Builder().config(merchantConfig.getRSAConfig(storeId)).build();
//                GetTransferBatchByOutNoRequest request = new GetTransferBatchByOutNoRequest();
//                TransferBatchEntity response;
//                RecordDetailsModel newRecordDetailsModel;
//                for (WithdrawModel model : list) {
//                    request.setOutBatchNo(model.getTxsno());
//                    request.setNeedQueryDetail(Boolean.FALSE);
//                    try {
//                        response = service.getTransferBatchByOutNo(request);
//                    } catch (ServiceException e) {
//                        // http请求成功，但是接口失败，这里需要根据实际需求处理错误码
//                        logger.error("商家转账到零钱查询批次转账单结果错误!商家订单号:" + model.getTxsno());
//                        logger.error("错误信息:" + e.getErrorCode() + "," +  e.getErrorMessage());
//                        throw new LaiKeAPIException(e.getErrorCode(), e.getErrorMessage());
//                    } catch (LaiKeAPIException e) {
//                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "QueryBatchTransferOrder");
//                    }
//                    if (response.getTransferBatch().getBatchStatus().equals(WithdrawModel.BATCH_STATUS.FINISHED)) {
//                        // 已完成。批次内的所有转账明细单都已处理完成
//                        successNum++;
//                        //修改提现状态和消息通知状态
//                        model.setWxStatus(WithdrawModel.WX_STATUS.SUCCESS);
//                    }else if (response.getTransferBatch().getBatchStatus().equals(WithdrawModel.BATCH_STATUS.CLOSED)){
//                        // 已关闭。可查询具体的批次关闭原因确认
//                        failNum++;
//                        logger.error("商家转账到零钱失败!商家订单号:" + model.getTxsno());
//                        logger.error("商家转账到零钱失败!错误原因:" + response.getTransferBatch().getCloseReason());
//                        logger.info("商家转账到零钱失败,开始退还零钱");
//                        //将提现金额退还
//                        model.setWxStatus(WithdrawModel.WX_STATUS.FAIL);
//                        model.setRefuse("微信余额打款失败,余额退回");
//                        User user = userBaseMapper.selectByUserId(storeId, model.getUser_id());
//                        if (user == null){
//                            logger.error("微信余额打款失败,余额退回{}用户不存在", model.getUser_id());
//                            continue;
//                        }
//                        if (model.getIs_mch() == 1){
//                            MchModel mchModel = mchModelMapper.selectByPrimaryKey(user.getMchId());
//                            //退还到钱包
//                            int count = mchModelMapper.refuseWithdraw(mchModel.getId(), model.getMoney());
//                            if (count < 1) {
//                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TXSB, "提现失败");
//                            }
//                        }else {
//                            //退还至余额
//                            int count = userBaseMapper.rechargeUserPrice(user.getId(), model.getMoney().abs());
//                            if (count < 1) {
//                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_FWQFMQSHZS, "服务器繁忙,请稍后重试");
//                            }
//                            user = userBaseMapper.selectByPrimaryKey(user.getId());
//                            //原来的提现记录
//                            RecordDetailsModel recordDetailsModel = new RecordDetailsModel();
//                            recordDetailsModel.setStore_id(vo.getStoreId());
//                            recordDetailsModel.setsNo(model.getTxsno());
//                            recordDetailsModel = recordDetailsModelMapper.selectOne(recordDetailsModel);
//                            //余额退还记录
//                            newRecordDetailsModel = new RecordDetailsModel();
//                            newRecordDetailsModel.setStore_id(vo.getStoreId());
//                            newRecordDetailsModel.setMoney(model.getMoney().abs());
//                            newRecordDetailsModel.setUserMoney(user.getMoney());
//                            newRecordDetailsModel.setMoneyType(RecordDetailsModel.moneyType.INCOME);
//                            newRecordDetailsModel.setType(RecordDetailsModel.type.WITHDRAWAL_OF_BALANCE);
//                            newRecordDetailsModel.setsNo(recordDetailsModel.getsNo());
//                            newRecordDetailsModel.setWithdrawalFees(recordDetailsModel.getWithdrawalFees());
//                            newRecordDetailsModel.setWithdrawalMethod(recordDetailsModel.getWithdrawalMethod());
//                            newRecordDetailsModel.setRecordTime(new Date());
//                            newRecordDetailsModel.setAddTime(new Date());
//                            recordDetailsModelMapper.insert(newRecordDetailsModel);
//
//                            RecordModel recordModel = new RecordModel();
//                            recordModel.setStore_id(vo.getStoreId());
//                            recordModel.setUser_id(model.getUser_id());
//                            recordModel.setMoney(model.getMoney());
//                            recordModel.setOldmoney(user.getMoney());
//                            recordModel.setEvent(String.format("%s微信提现%s失败", user.getUser_id(), model.getMoney()));
//                            recordModel.setType(22);
//                            recordModel.setDetails_id(newRecordDetailsModel.getId());
//                            recordModel.setAdd_date(new Date());
//                            recordModelMapper.insertSelective(recordModel);
//                        }
//                    }
//                    withdrawModelMapper.updateByPrimaryKeySelective(model);
//                }
//
//                logger.info("商城id: {}, 商城商家转账到零钱已完成订单数量{}",storeId, successNum);
//                logger.info("商城id: {}, 商城商家转账到零钱失败订单数量{}",storeId, failNum);
//            }
//        }catch (LaiKeAPIException l) {
//            logger.error("商家转账到零钱查询批次转账单结果", l);
//            throw l;
//        }catch (Exception e) {
//            logger.error("商家转账到零钱查询批次转账单结果 ", e);
//            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "QueryBatchTransferOrder");
//        }
//    }
//
//    public boolean MerchantTransfersToChange(Integer storeId, String withdrawId, String pluginStatus){
//        Map<String, Object> resultMap = new HashMap<>(16);
//        try {
//            //FX
//            DistributionWithdrawModel distributionWithdrawModel = null;
//            String userId = "";
//            BigDecimal Money = BigDecimal.ZERO;
//            BigDecimal s_charge = BigDecimal.ZERO;
//            String OutBatchNo = "";
//            String OutDetailNo = "";
//            String realName = "";
//            if (pluginStatus.equals(DictionaryConst.OrdersType.ORDERS_HEADER_FX)){
//                distributionWithdrawModel = distributionWithdrawModelMapper.selectByPrimaryKey(withdrawId);
//                if (distributionWithdrawModel == null){
//                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TXJLBCZ, "提现记录不存在");
//                }
//                if (distributionWithdrawModel.getWithdrawStatus().equals(WithdrawModel.WITHDRAW_STATUS.YHK)){
//                    logger.error("【微信零钱提现】提现申请id{}，为银行卡提现", withdrawId);
//                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SJCW, "数据错误");
//                }
//                userId = distributionWithdrawModel.getUser_id();
//                Money = distributionWithdrawModel.getMoney();
//                s_charge = distributionWithdrawModel.getS_charge();
//                OutBatchNo = BuilderIDTool.getNext(BuilderIDTool.Type.ALPHA, 12);
//                OutDetailNo = BuilderIDTool.getNext(BuilderIDTool.Type.ALPHA, 10);
//                realName = distributionWithdrawModel.getRealname();
//            }
//            //获取用户信息
//            User user = userBaseMapper.selectByUserId(storeId, userId);
//            if (user == null){
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_YHBCZ, "用户不存在");
//            }
//            String paymentJson = paymentConfigModelMapper.getPaymentConfigInfo(storeId, "wechat_v3_withdraw");
//            paymentJson = URLDecoder.decode(paymentJson, GloabConst.Chartset.UTF_8);
//            JSONObject payJson = JSONObject.parseObject(paymentJson);
//            //微信SDK提供
//            TransferBatchService service =
//                    new TransferBatchService.Builder().config(merchantConfig.getRSAConfig(storeId)).build();
//            InitiateBatchTransferRequest request = new InitiateBatchTransferRequest();
//            String batchName = "";
//            String BatchRemark = "";
//            //用户提现
//            batchName = "用户余额提现";
//            BatchRemark =user.getUser_name() + "用户进行"  + batchName;
//            //微信金额单位分处理
//            BigDecimal yb = new BigDecimal("100");
//            BigDecimal totalAmount = Money.subtract(s_charge);
//            if (totalAmount.compareTo(BigDecimal.ZERO) > 0){
//                totalAmount = totalAmount.multiply(yb);
//            }else {
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SJCW, "数据错误");
//            }
//            //构造请求微信支付发起转账的参数
//            //【批次名称】 该笔批量转账的名称
//            request.setBatchName(batchName);
//            //【商户appid】 申请商户号的appid或商户号绑定的appid（企业号corpid即为此appid）
//            request.setAppid(payJson.getString("appid"));
//            //【商家批次单号】 商户系统内部的商家批次单号，要求此参数只能由数字、大小写字母组成，在商户系统内部唯一
//            request.setOutBatchNo(OutBatchNo);
//            //【批次备注】 转账说明，UTF8编码，最多允许32个字符
//            request.setBatchRemark(BatchRemark);
//            //【转账总金额】 转账金额单位为“分”。转账总金额必须与批次内所有明细转账金额之和保持一致，否则无法发起转账操作
//            request.setTotalAmount(totalAmount.longValue());
//            //【转账总笔数】 一个转账批次单最多发起一千笔转账。转账总笔数必须与批次内所有明细之和保持一致，否则无法发起转账操作
//            request.setTotalNum(1);
//
//
//            List<TransferDetailInput> transferDetailInputs = new ArrayList<>();
//            TransferDetailInput transferDetailInput = new TransferDetailInput();
//            //【收款用户openid】 商户appid下，某用户的openid
//            transferDetailInput.setOpenid(user.getWx_id());
//            //【商家明细单号】 商户系统内部区分转账批次单下不同转账明细单的唯一标识，要求此参数只能由数字、大小写字母组成
//            transferDetailInput.setOutDetailNo(OutDetailNo);
//            //【转账金额】 转账金额单位为“分”
//            transferDetailInput.setTransferAmount(totalAmount.longValue());
//            //【转账备注】 单条转账备注（微信用户会收到该备注），UTF8编码，最多允许32个字符
//            transferDetailInput.setTransferRemark(BatchRemark);
//            if (Money.compareTo(new BigDecimal(2000)) >= 0
//                    && StringUtils.isNotEmpty(realName)){
//                transferDetailInput.setUserName(realName);
//            }
//
//            transferDetailInputs.add(transferDetailInput);
//            //【转账明细列表】 发起批量转账的明细列表，最多一千笔
//            request.setTransferDetailList(transferDetailInputs);
//            try {
//                InitiateBatchTransferResponse response = service.initiateBatchTransfer(request);
//                //【微信批次单号】 微信批次单号，微信商家转账系统返回的唯一标识
//                String batchId = response.getBatchId();
//                if (pluginStatus.equals(DictionaryConst.OrdersType.ORDERS_HEADER_FX)){
//                    distributionWithdrawModel.setWxOpenId(user.getWx_id());
//                    distributionWithdrawModel.setWxName(user.getWx_name());
//                    distributionWithdrawModel.setWxSon(batchId);
//                    distributionWithdrawModel.setWxStatus(WithdrawModel.WX_STATUS.SUCCESS);
//                    distributionWithdrawModelMapper.updateByPrimaryKeySelective(distributionWithdrawModel);
//                }
//            } catch (ServiceException e) {
//                // http请求成功，但是wx接口失败，这里需要根据实际需求处理错误码
//                logger.error("商家转账到零钱错误!");
//                logger.error("错误信息:" + e.getErrorCode() + "," +  e.getErrorMessage());
//                //管理后台消息通知
//                MessageLoggingModal messageLoggingSave = new MessageLoggingModal();
//                messageLoggingSave.setStore_id(storeId);
//                messageLoggingSave.setMch_id(user.getMchId());
//                messageLoggingSave.setTo_url("");
//                messageLoggingSave.setAdd_date(new Date());
//                if (e.getErrorCode().equals("403")){
//                    //商户账户资金不足，请充值后原单重试，请勿更换商家转账批次单号
//                    messageLoggingSave.setType(MessageLoggingModal.Type.TYPE_USER_WITHDRAWAL);
//                    messageLoggingSave.setParameter(user.getUser_name());
//                    messageLoggingSave.setContent(String.format("ID为%s的用户申请提现打款余额不足，请及时充值！", user.getUser_id()));
//                }else {
//                    messageLoggingSave.setType(MessageLoggingModal.Type.TYPE_USER_WITHDRAWAL);
//                    messageLoggingSave.setParameter(user.getUser_name());
//                    messageLoggingSave.setContent(String.format("ID为%s的用户申请提现打款失败，失败原因:%s",user.getUser_id(),e.getErrorMessage()));
//                }
//                messageLoggingModalMapper.insertSelective(messageLoggingSave);
//                throw new LaiKeAPIException(e.getErrorCode(), e.getErrorMessage());
//            } catch (LaiKeAPIException l) {
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "MerchantTransfersToChange");
//            }
//        }catch (LaiKeAPIException l) {
//            logger.error("商家转账到零钱异常", l);
//            throw l;
//        }catch (Exception e) {
//            logger.error("商家转账到零钱异常 ", e);
//            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "MerchantTransfersToChange");
//        }
//        return true;
//    }
//
//    @Autowired
//    private DistributionWithdrawModelMapper distributionWithdrawModelMapper;
//}
